package name.vaccari.matteo.tai.phonedirectory.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Map;

public class HttpRequest {
	private String path;
	private String method;
	private Map<String, String> headers = new HashMap<String, String>();
	private String body;
	private Map<String, String> params = new HashMap<String, String>();

	public HttpRequest(Reader reader) throws IOException {
		BufferedReader bufferedReader = new BufferedReader(reader);
		parseStatusLine(bufferedReader);
		parseHeaders(bufferedReader);
		parseBody(bufferedReader);
		parseParams();
	}

	private void parseParams() {
		if ("".equals(body)) return;
		String[] pairs = body.split("&");
		for (int i=0; i<pairs.length; i++) {
			String[] split = pairs[i].split("=", 2);
			String key = split[0];
			String value = split[1];
			params.put(key, value);
		}
	}

	private void parseBody(BufferedReader bufferedReader) throws IOException {
		char[] buffer = new char[10000];
		int read = bufferedReader.read(buffer);
		this.body = (-1 == read) ? "" : new String(buffer, 0, read);
	}

	private void parseHeaders(BufferedReader bufferedReader) throws IOException {
		String line;
		while ((line = bufferedReader.readLine()).length() > 0) {
			String[] split = line.split(":", 2);
			String key = split[0].toLowerCase();
			String value = split[1].trim();
			headers.put(key, value);
		}
	}

	private void parseStatusLine(BufferedReader bufferedReader)
			throws IOException {
		String statusLine = bufferedReader.readLine();
		String[] split = statusLine.split(" ");
		method = split[0];
		path = split[1];
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getMethod() {
		return method;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	public Map<String, String> getParams() {
		return this.params ;
	}

	public String getHeader(String name) {
		return headers.get(name);
	}

	public String getBody() {
		return body;
	}
}
